package com.mbf.crm.controller.system;


import java.util.ArrayList;

import javax.validation.Valid;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mbf.crm.common.AjaxResult;
import com.mbf.crm.common.DataGrid;
import com.mbf.crm.model.dao.ResourceDao;
import com.mbf.crm.model.dao.RoleDao;
import com.mbf.crm.model.domain.Resource;
import com.mbf.crm.model.domain.Role;
import com.mbf.crm.service.ResourceService;

/**
 * 角色控制器
 * @author 晏鼠  张劲松
 *
 */
@Controller
@RequestMapping("/system/role")
//指定事务是否为只读事务，默认值为 false；为了忽略那些不需要事务的方法，比如读取数据，可以设置 read-only 为 true。
@Transactional(readOnly = true)
public class RoleController {

	Logger logger = Logger.getLogger(RoleController.class);
	
	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private ResourceService resourceService;
	
	@Autowired
	private ResourceDao resourceDao;
	
	@RequestMapping
	public void index(){
	}
	
	@RequestMapping("/list")
	@ResponseBody
	public DataGrid<Role> list(){
		return new DataGrid<Role>(roleDao.findAll(new Sort(Direction.DESC, "id")));
	}
	
	@RequestMapping({"/save","/update"})
	@Transactional
	@ResponseBody
	public Object save(@Valid Role role,BindingResult br){
		if(br.hasErrors()){
			logger.error("对象校验失败：" + br.getAllErrors());
			return new AjaxResult(false).setData(br.getAllErrors());
		}else{
			role.setResource(null);
			return roleDao.save(role);
		}
	}
	
	@RequestMapping("/delete")
	@Transactional
	@ResponseBody
	public AjaxResult delete(Long id){
		try{
			roleDao.deleteById(id);
		}catch(Exception e){
			return new AjaxResult().setMessage(e.getMessage());
		}
		return new AjaxResult();
	}
	
	@RequestMapping("/resource/tree")
	@ResponseBody
	public Iterable<Resource> resourceTree(){
		return resourceService.getResourceTree();
	}
	
	/**
	 * 角色关联资源
	 * @param roleId
	 * @param resourceId
	 * @return
	 */
	@RequestMapping("/resource/save")
	@Transactional
	@ResponseBody
	public AjaxResult resourceSave(Long roleId,Long[] resourceId){
		Role role = roleDao.findOne(roleId);
		if(role != null && resourceId != null && resourceId.length > 0){
			try{
				role.setResource(new ArrayList<Resource>());
				for (Long rid : resourceId) {
					if(rid != null){
						//将资源关联到角色
						role.getResource().add(resourceDao.findOne(rid));
					}
				}
				roleDao.save(role);
			}catch(Exception e){
				logger.error("角色资源关联错误",e);
			}
		}
		return new AjaxResult(false, "关联失败！");
	}
	
}
